package com.engine.modules.ytht.mapper;

import com.alibaba.fastjson.JSONObject;
import com.engine.common.baseEntity.gis.BoxRangeEntity;
import com.engine.common.exception.MapperException;
import com.engine.common.exception.ServiceException;
import com.engine.common.exception.SystemTableException;
import com.engine.common.util.BasicParamUtil.StringUtils;
import com.engine.common.util.CacheUtil.MyCacheUtil;
import com.engine.common.util.GeoUtil.GeomCaculateUtil;
import com.engine.common.util.ListMapAndJson;
import com.engine.common.util.UUIDUtil;
import com.engine.init.Globle;
import com.engine.init.entity.GroupPropertiesEntity;
import com.engine.init.entity.TablePropertieEntity;
import com.engine.init.entity.TableToGroupEntity;
import com.engine.modules.general.mapper.GeneralDataCommonMapper;
import com.engine.modules.ytht.entity.FieldBlockUpdateResultEntity;
import com.engine.modules.ytht.entity.PlotInfoEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.regex.Pattern;

/**
 * @author FY
 * @version 1.0.0
 * @ClassName FieldBlockBindingMapper.java
 * @Description TODO
 * @createTime 2021年12月10日
 */
@Repository
@Slf4j
public class FieldBlockBindingMapper {

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Autowired
    GeneralDataCommonMapper generalDataCommonMapper;

    @Autowired
    CacheManager cacheManager;

    @Transactional
    public String fieldBlockBindingInsertByMapGeoJson(String tablePac, Map<String, Object> map, String tableName) {
        if (Globle.TablePropertiesMap.get(tableName) == null)
            throw new NullPointerException("数据库中表不存在或未添加进数据目录");
        String uuid = ListMapAndJson.getUUID32();
        Set<String> set = map.keySet();            //得到由键组成的Set集合
        Iterator<String> it = set.iterator();
        String inputColums = "";
        String inputValue = "";
        List<Object> largs = new ArrayList<>();
        largs.add(map.get("geom"));
        while (it.hasNext()) {
            String key = it.next();
            if (key.equals("id") || key.equals("gmt_update") || key.equals("gmt_create")
                    || key.equals("del_flag") || key.equals("geom") || key.equals("field_black_no")
                    || key.equals("table_pac")|| key.equals("field_source_type")|| key.equals("increment_dkbm")
                    || key.equals("field_cross_nos"))
                continue;
            inputColums += key + ",";
            inputValue += "?,";
            if (key.contains("time")) {
                try {
                    largs.add(new Date((Long) map.get(key)));
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                    largs.add(null);
                }
            } else
                largs.add(map.get(key));
        }
        inputColums += "id,";
        inputValue += "?,";
        largs.add(uuid);
        inputColums = inputColums.substring(0, inputColums.length() - 1);
        inputValue = inputValue.substring(0, inputValue.length() - 1);
        JSONObject js = JSONObject.parseObject(map.get("geom").toString());
        String gstr = "ST_GeomFromGeoJSON(?)";
        if (js.getString("type").contains("Polygon"))
            gstr = "ST_Multi(ST_GeomFromGeoJSON(?))";
        String sql =
                "insert into " + tableName + " (gmt_update,gmt_create,del_flag,table_pac,field_source_type,geom," + inputColums + ") " +
                        "values (NOW(), NOW(), 0,'" + tablePac + "','2'," + gstr + "," + inputValue + ")";
        log.debug(sql);
        int flag = jdbcTemplate.update(sql, largs.toArray());
        sql = "UPDATE " + tableName + " SET field_black_no=table_pac||lpad(cast(increment_dkbm as VARCHAR), 9, '0')"
                + " WHERE id='"+uuid+"'";
        jdbcTemplate.update(sql);
        if (flag == 1)
        {
            return selectFieldblackNoById(uuid,tableName);
        }
        else
            return "";
    }
    @Transactional
    public String fieldBlockBindingUpdateByMapGeoJson(String tablePac,Map<String, Object> map, String tableName, String authCo) {
        if (Globle.TablePropertiesMap.get(tableName) == null)
            throw new NullPointerException("数据库中表不存在或未添加进数据目录");
        String pacSql = "";
        if (Globle.TablePropertiesMap.get(tableName).getPermissionControl())
            pacSql += " AND (LEFT(pac," + authCo.length() + ")='" + authCo + "' OR pac IS NULL)";
        Set<String> set = map.keySet();            //得到由键组成的Set集合
        Iterator<String> it = set.iterator();
        String optSeq = "";
        List<Object> lars = new ArrayList<>();
        String fbId=map.get("field_black_no").toString();
        lars.add(map.get("geom"));
        while (it.hasNext()) {
            String key = it.next();
            if (key.equals("id") || key.equals("gmt_update") || key.equals("gmt_create") || key.equals("del_flag")
                    || key.equals("geom")|| key.equals("field_black_no")|| key.equals("field_cross_nos")
                    || key.equals("table_pac")|| key.equals("field_source_type")|| key.equals("increment_dkbm"))
                continue;
            if (key.contains("time")) {
                try {
                    lars.add(new Date((Long) map.get(key)));
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                    lars.add(null);
                }
                optSeq += key + "=?,";
                continue;
            }
            optSeq += key + "=?,";
            lars.add(map.get(key));
        }
        optSeq = optSeq.substring(0, optSeq.length() - 1);
        log.info(optSeq);
        String sql = "update " + tableName +
                " set gmt_update=NOW()," +
                "del_flag='0'," +
                "field_source_type='2'," +
                "geom=ST_GeomFromGeoJSON(?)," +
                "table_pac='"+tablePac+"',"+
                optSeq +
                " where field_black_no = '" + fbId + "' " + pacSql;
        int count = jdbcTemplate.update(sql, lars.toArray());
        log.info(sql);
        if (count == 0)
            return "";
        else
            return fbId;
    }

    public String deleteLogicByFbId(String fbId, String tableName, String authCo) {
        if (Globle.TablePropertiesMap.get(tableName) == null)
            throw new NullPointerException("数据库中表不存在或未添加进数据目录");
        String pacSql = "";
        pacSql += " AND (LEFT(pac," + authCo.length() + ")='" + authCo + "' OR pac IS NULL)";
        String sql = "update " + tableName + " set del_flag = '1',gmt_update=NOW() where field_black_no=?" + pacSql;
        int r = jdbcTemplate.update(sql, fbId);
        if (r > 0)
            return fbId;
        else
            return "";
    }

    public String deleteByFbId(String fbId, String tableName, String authCo) {
        if (Globle.TablePropertiesMap.get(tableName) == null)
            throw new NullPointerException("数据库中表不存在或未添加进数据目录");
        String pacSql = "";
        if (Globle.TablePropertiesMap.get(tableName).getPermissionControl())
            pacSql += " AND (LEFT(pac," + authCo.length() + ")='" + authCo + "' OR pac IS NULL)";
            String sql = "DELETE FROM " + tableName + " WHERE field_black_no = ? "+ pacSql;
            log.debug(sql);
            int x=jdbcTemplate.update(sql,fbId);
            if(x==1)
                return fbId;
            else
                return "";
    }

    public String checkVectorError(String geometery) {
        String IsValidGeom = "SELECT st_IsValidReason(st_geomfromgeojson(?)) as result limit 1";
        Map<String, Object> rs = jdbcTemplate.queryForMap(IsValidGeom, geometery);
        String str = (String) rs.get("result");
        return str;
    }

    public List<String> getIntersectsBlockFbId(String geometery,String tableName)
    {
        String sql = "SELECT field_black_no FROM "+tableName+" WHERE st_intersects(st_geomfromgeojson(?),geom) AND del_flag='0';";
        List<String> strings = jdbcTemplate.queryForList(sql, String.class, geometery);
        return strings;
    }

    public String selectIdByFieldblackNo(String fieldBlockNo) {
        if(!Pattern.matches(fieldBlockNo, "53[0-9]{13}"))
            throw new MapperException("fieldblackNo不合规");
        String tablePac=fieldBlockNo.substring(0,6);
        String groupName = "b_gis_polygon_qqcg_x";
        String tableName=groupName+tablePac;
        if (Globle.TablePropertiesMap.get(tableName) == null)
            throw new NullPointerException("数据库中表不存在或未添加进数据目录");
        String sql="SELECT id FROM "+tableName+" WHERE field_black_no=?";
        try{
            String rs=jdbcTemplate.queryForObject(sql,String.class,fieldBlockNo);
            return rs;
        }catch (Exception e)
        {
            return "";
        }
    }

    public String selectFieldblackNoById(String id,String tableName) {
        if(!StringUtils.checkUuidV2(id))
            throw new MapperException("id不合规");
        if (Globle.TablePropertiesMap.get(tableName) == null)
            throw new NullPointerException("数据库中表不存在或未添加进数据目录");
        String sql="SELECT field_black_no FROM "+tableName+" WHERE id=?";
        try{
            String rs=jdbcTemplate.queryForObject(sql,String.class,id);
            return rs;
        }catch (Exception e)
        {
            return "";
        }
    }
}
